const user = require('../models/userDetail')

var express = require('express');
var router = express.Router();

const sendMail = require('../email/email')

const encryptedPassword = ( pwd) => {
  let md5 = require('js-md5');
  let pwdkey = md5("{{{" + pwd + "}" );
  return pwdkey;
}

const formidable = require('formidable');

router.post('/', (req, res, next)=>{
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files){
    if(err){
        res.json({'state': false});
    }else{
      user.find({
        // username: fields.username,
        stuNo: fields.stuNo,
        school: fields.schoolName
      }, {
        email:1,
        username: 1
      }, (err, stuEmail) => {
        if(err){
          res.json({'state': false, 'msg' : 'The student is not exist!'});
        } else {
          if(stuEmail.length === 0) {
            res.json({'state': false, 'msg' : '学校或学号错误!'});
          } else {
            function randomPassword(size) {
              //生成随机密码
              var seed = new Array(
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
                'a','b','c','d','e','f','g','h','i','j','k','m','n','p','Q','r','s','t','u','v','w','x','y','z',
                '0','1','2','3','4','5','6','7','8','9'
              );
              seedlength = seed.length;//数组长度
              var createPassword = '';
              for (i=0;i<size;i++) {
                j = Math.floor(Math.random()*seedlength);
                createPassword += seed[j];
              }
              return createPassword;
            }
            let newpassword = randomPassword(6)
  
            //修改密码
            user.findOneAndUpdate({ stuNo: fields.stuNo }, {
              $set: {
                password: encryptedPassword(newpassword)
              }
            }, { new: true }, (err, doc)=>{
              if(err){
                res.json({'statee':false, 'msg':'the lesson is not exist!'});
              }else{
                let cb = function (e) {
                  if(e === true) {
                    res.json({
                      'state': true, 
                      'emailflag': true
                    });
                  } else {
                    res.json(e);
                  }
                }
                // console.log(stuEmail[0].email)
                if(stuEmail[0].email !== undefined && stuEmail[0].email !== ''){
                  // console.log(`${ stuEmail[0].email }`)
                  sendMail(
                    stuEmail[0].email,
                    '密码重置提醒', 
                    `<div>Hi,您在涅槃之路的密码已被重置，您的用户名是 ${ stuEmail[0].username } ，新的密码是 ${ newpassword } ,请在登陆网站后第一时间修改您的登录密码！</div>`,
                    cb
                  );
                } else {
                  res.json({
                    'state': true, 
                    'emailflag': false,
                    'newpassword': newpassword,
                    'username': stuEmail[0].username
                  });
                }
              }
            })
          }
          

        }
      })
    }
  });
});

module.exports = router;